package response

import (
	"github.com/gin-gonic/gin"
	"go-admin-server/common/base"
	"go-admin-server/common/errors"
	"go-admin-server/common/logger"
	"go-admin-server/common/utils"
	"net/http"
)

func Ok(ctx *gin.Context) {
	ctx.JSON(http.StatusOK, gin.H{"code": 0, "message": "请求成功"})
}

func Success(ctx *gin.Context, data interface{}) {
	ctx.JSON(http.StatusOK, gin.H{"code": 0, "data": data, "message": "请求成功"})
}

func SuccessPage(ctx *gin.Context, page, size, count int, list interface{}) {
	result := base.Result{Code: 0, Message: "请求成功", Data: list}
	pages := utils.CalculatePage(count, size)
	pageInfo := base.PageInfo{Page: page, Size: size, Pages: pages, Total: count}
	pageResult := base.PageResult{
		Result:   result,
		PageInfo: pageInfo,
	}
	ctx.JSON(http.StatusOK, pageResult)
}

func Fail(ctx *gin.Context, code int, message string) {
	//val, _ := ctx.Get(base.UserContextKey)
	ctx.JSON(http.StatusOK, gin.H{"code": code, "message": message})
}

func Error(ctx *gin.Context, err error) {
	var res *errors.ResponseError

	if err != nil {
		if e, ok := err.(*errors.ResponseError); ok {
			res = e
		} else {
			res = errors.UnWrapResponse(errors.ErrInternalServer)
			res.ERR = err
		}
	} else {
		res = errors.UnWrapResponse(errors.ErrInternalServer)
	}

	if err := res.ERR; err != nil {
		if res.Message == "" {
			res.Message = err.Error()
		}
		if status := res.Code; status >= 400 && status < 500 {
			logger.WithContext(ctx).Warnf(err.Error())
		} else if status >= 500 {
			logger.WithContext(logger.NewStackContext(ctx, err)).Errorf(err.Error())
		}
	}

	Fail(ctx, res.Code, res.Message)
}
